package club.zhilin.guli.service.vod.controller.admin;

import club.zhilin.guli.common.base.result.CommonResult;
import club.zhilin.guli.common.base.result.CommonResultCodeEnum;
import club.zhilin.guli.service.base.exception.GlobalException;
import club.zhilin.guli.service.vod.service.IVideoService;
import com.aliyuncs.exceptions.ClientException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author zhilin
 * @since 2022/2/11 20:58
 */
@Api(tags = "阿里云视频点播服务")
@Slf4j
@RestController
@RequestMapping("/admin/vod/media")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MediaController {

    private final IVideoService iVideoService;

    @ApiOperation("上传视频接口")
    @PostMapping("/upload")
    public CommonResult<String> uploadVideo(@RequestParam("file") MultipartFile file) {
        String videoId;
        try {
            videoId = iVideoService.uploadVideo(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GlobalException(CommonResultCodeEnum.VIDEO_UPLOAD_TOMCAT_ERROR);
        }
        return CommonResult.success("视频上传成功", videoId);
    }

    @ApiOperation("批量删除视频")
    @DeleteMapping("/video/{ids}")
    public CommonResult<String> removeVideo(@PathVariable("ids") String ids) {
        try {
            iVideoService.removeVideo(ids);
        } catch (ClientException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GlobalException(CommonResultCodeEnum.VIDEO_DELETE_ALIYUN_ERROR);
        }
        return CommonResult.success("视频删除成功");
    }

    @ApiOperation("获取播放凭证")
    @GetMapping("/videoAuth/{id}")
    public CommonResult<String> playAuth(@PathVariable String id) {
        String auth;
        try {
            auth = iVideoService.getPlayAuth(id);
        } catch (ClientException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GlobalException(CommonResultCodeEnum.FETCH_PLAY_AUTH_ERROR);
        }
        return CommonResult.success("获取播放凭证成功", auth);
    }
}
